<template>
  <div>
    <div class="wrapper">
      <input v-model="keyword" type="text" placeholder="请输入城市名或拼音">
    </div>
    <div class="search-result" v-show="keyword">
      <ul>
        <li class="result-item" @click="handleClick(item.name)" v-for="(item, index) of list" :key="index">
          {{item.name}}
        </li>
        <li class="result-item" v-show="hasNoData">
          该城市暂未开通服务，敬请期待~
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CitySearch',
  props: {
    searchData: Object
  },
  data () {
    return {
      keyword: '',
      list: []
    }
  },
  methods: {
    handleClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  watch: {
    keyword () {
      if (!this.keyword) {
        this.list = []
        return
      }
      const result = []
      const alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z']
      alphabet.forEach((letter) => {
        const cityList = this.searchData[letter].content
        cityList.forEach((item) => {
          if (item.name.indexOf(this.keyword) > -1 || item.spell.indexOf(this.keyword) > -1) {
            result.push(item)
          }
        })
      })
      this.list = result
    }
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/variables.styl'
  .wrapper
    height .6rem
    padding 0 1.2rem .1rem
    background-color $bgColor
    input
      width 100%
      height 100%
      text-align center
      color #666
      border-radius .1rem
  .search-result
    position absolute
    top 1.58rem
    left 0rem
    right 0rem
    text-align center
    border-bottom-left-radius .1rem
    border-bottom-right-radius .1rem
    background-color #fff
    z-index 9
    .result-item
      line-height .62rem
      color #212121
      border-bottom 1px solid #ccc
</style>
